const orderModel = appRequire('models/order');
const userModel = appRequire('models/user');

var md5 = require('md5');
module.exports = wxNotice

async function wxNotice(req, res) {
    var jsonData = req.body.xml;
    //console.log(jsonData)
    if (jsonData.result_code == 'SUCCESS') {
        var key = "xrXR1234567891234567891234567891"
        var stringA = "appid=" + jsonData.appid + "&bank_type=" + jsonData.bank_type + "&cash_fee=" + jsonData.cash_fee + "&fee_type=" + jsonData.fee_type +
            "&is_subscribe=" + jsonData.is_subscribe + "&mch_id=" + jsonData.mch_id + "&nonce_str=" + jsonData.nonce_str + "&openid=" +
            jsonData.openid + "&out_trade_no=" + jsonData.out_trade_no + "&result_code=" + jsonData.result_code + "&return_code=" +
            jsonData.return_code + "&time_end=" + jsonData.time_end + "&total_fee=" + jsonData.total_fee + "&trade_type=" +
            jsonData.trade_type + "&transaction_id=" + jsonData.transaction_id;
        var stringSignTemp = stringA + "&key=" + key;
        var sign = md5(stringSignTemp).toUpperCase();

        //验证成功
        if (sign == jsonData.sign) {
            await handleUserAndOrder(jsonData)
            var sendData = {
                return_code: 'SUCCESS',
                return_msg: 'OK'
            }
            res.end(json2Xml(sendData));
        }
    }
}

async function handleUserAndOrder(jsonData) {
   // console.log(jsonData)
    let orderDet = await orderModel.order.findOne({
        where: {
            out_trade_no: jsonData.out_trade_no
        }
    })

    orderDet = Common.clone(orderDet)
    console.log(orderDet)
    if (orderDet) {
        await orderModel.order.update({
            status: 1
        }, {
            where: {
                objectId: orderDet.objectId,
                out_trade_no: jsonData.out_trade_no
            }
        })

        let dataArr = orderDet.createdAt.split(" ");
        let yearDayArr = dataArr[0].split("-");
        let year = Number(yearDayArr[0])
        let month = Number(yearDayArr[1])
        let vipTime;

        //包月
        if (jsonData.total_fee == '1000') {
            if (month == 12) {
                year = year + 1
                month = "01"
            } else {
                month = month + 1
            }
            month = month < 10 ? ('0' + month) : month

            vipTime = year + "-" + month + "-" + yearDayArr[2] + " " + dataArr[1]
        }

        //包季度
        if (jsonData.total_fee == '5000') {
            if (month == 10) {
                year = year + 1
                month = "01"
            } else if (month == 11) {
                year = year + 1
                month = "02"
            } else if (month == 12) {
                year = year + 1
                month = "03"
            } else {
                month = month + 3
            }

            month = month < 10 ? ('0' + month) : month
            vipTime = year + "-" + month + "-" + yearDayArr[2] + " " + dataArr[1]
        }

        //包年
        if (jsonData.total_fee == '9800' || jsonData.total_fee == '12800') {
            year = year + 1
            month = month < 10 ? ('0' + month) : month
            vipTime = year + "-" + month + "-" + yearDayArr[2] + " " + dataArr[1]
        }

        let result = await userModel.user.update({
            vipTime: new Date(vipTime).getTime()
        }, {
            where: {
                objectId: orderDet.buyerId
            }
        })

        return result
    }
}

//json转xml
function json2Xml(json) {
    let _xml = '';
    Object.keys(json).map((key) => {
        _xml += `<${key}>${json[key]}</${key}>`
    })
    return `<xml>${_xml}</xml>`;
}